package com.example.demo.Provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.dto.GiteeUser;
import com.example.demo.dto.ProviderTokenDTO;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author redjava
 * @create 2021-07-20 12:33
 */
@Component
public class AccessProvider {
    public String getToken(ProviderTokenDTO providerTokenDTO) {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(client));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code&code=" + providerTokenDTO.getCode() + "&client_id=" + providerTokenDTO.getClient_id() + "&redirect_uri=" + providerTokenDTO.getRedirect_uri() + "&client_secret=" + providerTokenDTO.getClient_secret() + "")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            JSONObject object = JSON.parseObject(string);
            String access_token = (String) object.get("access_token");
            return access_token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public GiteeUser getUser(String Token) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token=" + Token)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            GiteeUser giteeUser = JSON.parseObject(string, GiteeUser.class);
            System.out.println(giteeUser);
            return giteeUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
